package com.player;

import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

public class MyCanvasFrame extends JFrame {

    private final ImageJpanel imageJpanel;
    private final Java2DFrameConverter converter = new Java2DFrameConverter();
    private final GraphicsDevice defaultScreenDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    private boolean isFullScreen = false;

    public MyCanvasFrame(String title) {
        super(title);
        imageJpanel = new ImageJpanel();
        setContentPane(imageJpanel);

    }


    public void init() {
        JFrame thisFrame = this;
        setUndecorated(true);
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension screenSize = tk.getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        setBounds(screenWidth >> 2 ,screenHeight >> 2, screenWidth >> 1, screenHeight >> 1);

        setVisible(true);
        imageJpanel.setFocusable(true);
        imageJpanel.requestFocusInWindow();
        imageJpanel.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!isFullScreen) {
                        defaultScreenDevice.setFullScreenWindow(thisFrame);
                        isFullScreen = true;
                    } else {
                        defaultScreenDevice.setFullScreenWindow(null);
                        isFullScreen = false;
                    }

                } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    System.exit(0);
                }
            }
        });


    }

    public void showImage(Frame frame) {
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        imageJpanel.setImage(bufferedImage);
        imageJpanel.setPtsTime(frame.timestamp);
        imageJpanel.updateUI();
    }

}
